//用户

/**
 * 编辑视图模型
 */
interface IUserDetailViewModel {
    /**
     * 编号
     */
    userId?: string;
    /**
     * 用户名
     */
    userName: string;
    /**
     * 车牌号
     */
    carCode: string;
    /**
     * 角色
     */
    roles?: string;
    /**
     * 实名头像
     */
    realHeadImage: string;
    /**
     * 实名头像状态
     */
    realHeadImageStatus: string;
    /**
     * 实名头像工具栏
     */
    realHeadImageTool: boolean;
    /**
     * 实名头像通过
     */
    clickOkPassState: boolean;
    /**
     * 实名头像不通过
     */
    clickRemovePassState: boolean;
    /**
     * 身份证
     */
    idCardImage: string;
    /**
     * 身份证状态
     */
    idCardImageSatus: string;
    /**
     * 身份证状态工具栏
     */
    idCardImageTool: boolean;
    /**
     * 身份证通过
     */
    clickIdCardOkPassState: boolean;
    /**
     * 身份证不通过
     */
    clickIdCardRemovePassState: boolean;
    /**
     * 驾驶证
     */
    drivingLicenseImage: string;
    /**
     * 驾驶证状态
     */
    drivingLicenseImageStatus: string;
    /**
     * 驾驶证状态工具栏
     */
    drivingLicenseImageTool: boolean;
    /**
     * 驾驶证通过
     */
    clickDrivingLicenseOkPassState: boolean;
    /**
     * 驾驶证不通过
     */
    clickDrivingLicenseRemovePassState: boolean;
    /**
     * 行驶证
     */
    vehicleLicenseImage: string;
    /**
     * 行驶证状态
     */
    vehicleLicenseImageStatus: string;
    /**
     * 行驶证工具栏
     */
    vehicleLicenseImageTool: boolean;
    /**
     * 行驶证通过
     */
    clickVehicleLicenseOkPassState: boolean;
    /**
     * 行驶证不通过
     */
    clickVehicleLicenseRemovePassState: boolean;
    /**
     * 说明
     */
    message: string;
    /**
     * 驾驶证状态提交
     */
    drivingLicenseCertificated: number;
    /**
     * 实名头像状态提交
     */
    realHeadImageCertificated: number;
    /**
     * 身份证提交
     */
    idCardCertificated: number;
    /**
     * 行驶证提交
     */
    vehicleLicenseCertificated: number;
    /**
     * 保存事件
     */
    click: () => void;
    /**
     * 通过的点击事件
     */
    clickOk: (statusValue: string) => void;
    /**
     * 表示通过样式
     */
    clickOkPass: (statusValue: string) => void;
    /**
     * 不允许通过的点击事件
     */
    clickRemove: (statusValue: string) => void;
    /**
     * 不允许通过样式
     */
    clickRemovePass: (status: string) => void;
    /**
     * 强制修改（跳转页面）
     */
    linkToUsersEdit: () => void;
}

/**
 * 模型视图
 */
interface IUserViewModel extends IBaseViewModel<IUserQueryTerms> {
    /**
     * 审核状态下拉
     */
    chekoutStateDropDown: Array<ValueListItemResponse>;
    /**
     * 角色下拉
     */
    rolesDropDown: Array<RolesListItemResponse>;
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<UserListItemResponse>;
    /**
     * 编辑视图
     */
    detail: IUserDetailViewModel;
    /**
     * 实名认证（编辑）
     */
    editUser: (user: UserListItemResponse) => void;
    /**
     * 启用
     */
    enableUser: (userId: string) => void;
    /**
     * 禁用
     */
    disableUser: (userId: string) => void;
    
    
}

/**
 * 查询条件
 */
interface IUserQueryTerms {
    /**
     * 关键字
     */
    searchingKeyWord: string;
    /**
     * 车牌号
     */
    searchingCarCode: string;
    /**
     * 起始时间
     */
    searchingStartTime: Date;
    /**
     * 结束时间
     */
    searchingEndTime: Date;
    /**
     * 角色
     */
    searchingRoleId: string;
    /**
     * 实名认证状态
     */
    searchingState: number;
    /**
     * 缓存
     */
    useCache: boolean;
}
class UserController extends ListController<IUserViewModel, IUserQueryTerms>{
    gridApi: uiGrid.IGridApiOf<UserListItemResponse>;

    constructor($scope: IUserViewModel, private $state: angular.ui.IStateService, private userService: IUserService, private rolesService: IRolesService, private valueService: IValueService, private $ngBootbox: BootboxService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();
        this.$scope.editUser = (row) => this.showEditUserDialog(row);
        this.$scope.enableUser =  this.showEnableUserDialog;
        this.$scope.disableUser = (userId) => this.showDisableUserDialog(userId);

        this.$scope.queryTerms = {
            searchingKeyWord: "",
            searchingCarCode: "",
            searchingStartTime: moment("0001-01-01").toDate(),
            searchingEndTime: new Date(),
            searchingRoleId: "",
            searchingState: null,
            useCache: false
        };

        this.$scope.gridOptions = {
            enableSorting: false,
            useExternalPagination: true,
            //useExternalSorting: true,
            enableColumnResizing: true,
            paginationPageSizes: [10, 20, 30],
            columnDefs: [
                { name: "序号", field: "index", enableColumnMenu: false },
                { name: "车牌号", field: "carNumber", enableColumnMenu: false },
                { name: "车型", field: "carType", enableColumnMenu: false },
                { name: "车长", field: "carLength", enableColumnMenu: false },
                { name: "用户名", field: "userName", enableColumnMenu: false },
                { name: "真实姓名", field: "realName", enableColumnMenu: false },
                { name: "实名认证状态", field: "realNameState", enableColumnMenu: false },
                { name: "实名申请时间", field: "certificationTime", enableColumnMenu: false },
                { name: "禁用", field: "isLockedout", enableColumnMenu: false },
                { name: "角色", field: "roles", enableColumnMenu: false },
                {
                    name: "操作",
                    cellFilter: "checkmark",
                    cellTemplate: '<a data-toggle="modal" data-target="#myModal" class="fa fa-edit m-l-xs primary text-info" title="编辑" ng-click="grid.appScope.editUser(row.entity)"></a> <a class="fa fa-check-circle primary text-success" ng-click="grid.appScope.enableUser(row.entity.userId)" title="启用" ng-hide="row.entity.isEnabled"></a> <a class="fa fa-minus-circle primary text-primary" ng-show="row.entity.isEnabled" title="禁用" ng-click="grid.appScope.disableUser(row.entity.userId)"></a>',
                    enableColumnMenu: false
                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
            }
        };

        this.query();
        this.loadChekoutStateDropDown();
        this.loadRolesDropDown();
    }
    
    loadData(queryTerms: IUserQueryTerms, skip: number, count: number): void {
        this.userService.getList(queryTerms.searchingKeyWord, queryTerms.searchingCarCode, queryTerms.searchingStartTime, queryTerms.searchingEndTime, queryTerms.searchingRoleId, queryTerms.searchingState, queryTerms.useCache, skip, count).then(result => {
            this.$scope.gridOptions.totalItems = result.data.total;
            this.$scope.gridOptions.data = result.data.list;

            if (skip == 0) {
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }
            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });
    }

    /**
     *加载审核状态 
     */
    loadChekoutStateDropDown(): void {
        this.$scope.chekoutStateDropDown = this.valueService.getCheckStateList().list;
    }
    /**
     * 加载角色
     */
    loadRolesDropDown(): void {
        this.rolesService.getList().then(result => {
            this.$scope.rolesDropDown = result.data.list;
        });
    }

    /**
     * 显示实名认证窗口（编辑）
     */
    showEditUserDialog(user: UserListItemResponse): void {
        this.$scope.title = "编辑";
        this.userService.getDetail(user.userId).then(result => {
            var obj = this.valueService.getCheckStateList().list;
            this.$scope.detail = {
                userId: user.userId,
                carCode: result.data.carCode,
                userName: user.realName || user.userName || user.phoneNumber,
                roles: user.roles,
                realHeadImageStatus: this.valueService.getCheckStateList().list[result.data.realHeadState].text,
                idCardImageSatus: this.valueService.getCheckStateList().list[result.data.idCardState].text,
                drivingLicenseImageStatus: this.valueService.getCheckStateList().list[result.data.drivingLicenseState].text,
                vehicleLicenseImageStatus: this.valueService.getCheckStateList().list[result.data.vehicleLicenseState].text,

                realHeadImage: result.data.realHeadImage || "img/a1.jpg",
                idCardImage: result.data.idCardImage || "img/a1.jpg",
                drivingLicenseImage: result.data.drivingLicenseImage || "img/a1.jpg",
                vehicleLicenseImage: result.data.vehicleLicenseImage || "img/a1.jpg",

                realHeadImageTool: result.data.realHeadState == 2 && result.data.realHeadImage !== null,
                idCardImageTool: result.data.idCardState == 2 && result.data.idCardImage !== null,
                drivingLicenseImageTool: result.data.drivingLicenseState == 2 && result.data.drivingLicenseImage !== null,
                vehicleLicenseImageTool: result.data.vehicleLicenseState == 2 && result.data.vehicleLicenseImage !== null,

                clickOkPassState: true,
                clickRemovePassState: true,

                clickIdCardOkPassState: true,
                clickIdCardRemovePassState: true,

                clickDrivingLicenseOkPassState: true,
                clickDrivingLicenseRemovePassState: true,

                clickVehicleLicenseOkPassState: true,
                clickVehicleLicenseRemovePassState: true,

                drivingLicenseCertificated: result.data.drivingLicenseState,
                realHeadImageCertificated: result.data.realHeadState,
                idCardCertificated: result.data.idCardState,
                vehicleLicenseCertificated: result.data.vehicleLicenseState,

                message: result.data.message,
                click: () => this.editUser(),
                clickOk: (statusValue) => this.statePassCheck('pass', statusValue, false),
                clickOkPass: (statusValue) => this.statePassCheck('pass', statusValue, true),
                clickRemove: (statusValue) => this.statePassCheck('remove', statusValue, null, false),
                clickRemovePass: (statusValue) => this.statePassCheck('remove', statusValue, null, true),
                linkToUsersEdit: this.linkToUsersEdit
            };
        });
    }

    editUser(): void {
        this.$ngBootbox.confirm("确定保存该数据吗？").then(e => {
            this.userService.putUserRealNameCertificationStatus(
                this.$scope.detail.userId,
                this.$scope.detail.carCode,
                this.$scope.detail.drivingLicenseCertificated,
                this.$scope.detail.realHeadImageCertificated,
                this.$scope.detail.idCardCertificated,
                this.$scope.detail.vehicleLicenseCertificated
            ).then(result => {
                this.query();
                $('#myModal').modal('hide');
            })
        })
    }
    /**
     * 启用
     */
    showEnableUserDialog = (userId: string) => {
        this.$ngBootbox.confirm("是否启用？").then(e => {
            this.userService.setAccountLockoutState(userId, false).then(result => {
                this.query();
            });
        });
    }
    /**
     * 禁用
     */
    showDisableUserDialog(userId: string): void {
        this.$ngBootbox.confirm("是否启用？").then(e => {
            this.userService.setAccountLockoutState(userId, true).then(result => {
                this.query();
            });
        });
    }
    /**
     * 跳转页面（强制修改）
     */
    linkToUsersEdit = () => {
        this.$state.go("app.management.user_edit", { userId: this.$scope.detail.userId, realName: this.$scope.detail.userName, roles: this.$scope.detail.roles });
        $('#myModal').modal('hide');
    }

    /**
     * 认状态函数
     */
    statePassCheck(way: string, statusValue: string, passValue?: boolean, dispassValue?: boolean): any {
        if (statusValue == 'RealHeadImage') {
            switch (way) {
                case 'pass':
                    return this.$scope.detail.clickOkPassState = passValue,
                    this.$scope.detail.realHeadImageCertificated = this.getStateResult(this.$scope.detail.clickRemovePassState, this.$scope.detail.clickOkPassState);
                case 'remove':
                    return this.$scope.detail.clickRemovePassState = dispassValue,
                    this.$scope.detail.realHeadImageCertificated = this.getStateResult(this.$scope.detail.clickRemovePassState, this.$scope.detail.clickOkPassState);
            }
        } else if (statusValue == 'IDCardImage') {
            switch (way) {
                case 'pass':
                    return this.$scope.detail.clickIdCardOkPassState = passValue,
                    this.$scope.detail.idCardCertificated = this.getStateResult(this.$scope.detail.clickIdCardRemovePassState, this.$scope.detail.clickIdCardOkPassState);
                case 'remove':
                    return this.$scope.detail.clickIdCardRemovePassState = dispassValue,
                    this.$scope.detail.idCardCertificated = this.getStateResult(this.$scope.detail.clickIdCardRemovePassState, this.$scope.detail.clickIdCardOkPassState);
            }
        } else if (statusValue == 'DrivingLicenseImage') {
            switch (way) {
                case 'pass':
                    return this.$scope.detail.clickDrivingLicenseOkPassState = passValue,
                        this.$scope.detail.drivingLicenseCertificated = this.getStateResult(this.$scope.detail.clickDrivingLicenseRemovePassState, this.$scope.detail.clickDrivingLicenseOkPassState);
                case 'remove':
                    return this.$scope.detail.clickDrivingLicenseRemovePassState = dispassValue,
                    this.$scope.detail.drivingLicenseCertificated = this.getStateResult(this.$scope.detail.clickDrivingLicenseRemovePassState, this.$scope.detail.clickDrivingLicenseOkPassState);
            }
        } else if (statusValue == 'vehicleLicenseImage') {
            switch (way) {
                case 'pass':
                    return this.$scope.detail.clickVehicleLicenseOkPassState = passValue,
                    this.$scope.detail.vehicleLicenseCertificated = this.getStateResult(this.$scope.detail.clickVehicleLicenseRemovePassState, this.$scope.detail.clickVehicleLicenseOkPassState);
                case 'remove':
                    return this.$scope.detail.clickVehicleLicenseRemovePassState = dispassValue,
                    this.$scope.detail.vehicleLicenseCertificated = this.getStateResult(this.$scope.detail.clickVehicleLicenseRemovePassState, this.$scope.detail.clickVehicleLicenseOkPassState);
            }
        }
    }
    /**
     * 实名认证状态转换（提交数据）
     */
    getStateResult(clickRemovePassState: boolean, clickOkPassState: boolean): number {
        if (clickRemovePassState == true && clickOkPassState == true) {
            return 2;
        } else if (clickRemovePassState == false) {
            return 4;
        } else if (clickOkPassState == false) {
            return 3;
        }
    };

}

app.controller('userController', ['$scope', '$state', 'userService', 'rolesService', 'valueService', '$ngBootbox', UserController]);
